import { login, logout, getInfo } from '@/api/login'
import {
  getToken,
  getRefreshToken,
  getExpires,
  getUserInfo,
  setToken,
  setRefreshToken,
  setExpires,
  setUserInfo,
  removeToken,
  removeRefreshToken,
  removeExpires,
  removeUserInfo,
} from '@/utils/auth'
import profileAvatar from '@/assets/images/profile.jpg'
import { jwtDecode } from 'jwt-decode'
const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    refreshToken: getRefreshToken(),
    expireTime: getExpires(),
    userInfo: {},
    avatar: profileAvatar,
    roles: [],
    isUserInfoLoaded: false, //代替roles字段,true标识用户信息拉取完成
    // permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            setToken(res.output.access_token)
            setRefreshToken(res.output.refresh_token)
            setExpires(new Date(res.output.expires).getTime())
            this.token = res.output.token
            this.refreshToken = res.output.refresh_token
            this.expireTime = res.output.expires
      
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // // 获取用户信息
    // getInfo() {
    //   return new Promise((resolve, reject) => {
    //     const token = getToken()
    //     // console.log('获取信息的时候，需要将token解析为信息', getToken())
    //     if (!token) {
    //       return reject('获取用户信息失败，请重新登陆')
    //     }
    //     const user = jwtDecode(getToken()).userInfo
    //     // console.log()
    //     const roles = ['admin']
    //     this.roles = roles
    //     this.userInfo = user
    //     setUserInfo(this.userInfo)
    //     return resolve()
    //   })
    // },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        try {
          const token = getToken()
          if (!token) {
            // 如果没有 Token，立即拒绝
            reject('获取用户信息失败，请重新登录')
            return
          }

          // 尝试解析用户信息
          const user = jwtDecode(token).userInfo
          if (!user) {
            throw new Error('Token无效，用户信息解析失败')
          }

          this.userInfo = user
          this.isUserInfoLoaded = true // 标记用户信息已加载
          setUserInfo(this.userInfo) // 缓存用户信息
          resolve(this.userInfo)
        } catch (error) {
          // 捕获解析或其他错误
          this.userInfo = {}
          this.isUserInfoLoaded = false
          removeToken() // 清除无效 Token
          removeUserInfo()
          reject(`获取用户信息失败：${error.message}`)
        }
      })
    },

    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        try {
          this.token = ''
          this.roles = []
          this.refreshToken = ''
          this.expireTime = ''
          this.userInfo = {}
          this.avatar = ''
          // this.permissions = []
          removeToken()
          removeExpires()
          removeRefreshToken()
          removeUserInfo()
          resolve()
        } catch (error) {
          reject(error)
        }
        ///记得放开
        // logout(this.token)
        //   .then(() => {
        //     this.token = ''
        //     this.roles = []
        //     this.permissions = []
        //     removeToken()
        //     resolve()
        //   })
        //   .catch((error) => {
        //     reject(error)
        //   })
      })
    },
  },
})

export default useUserStore
